package week_1.practice;
import java.util.Arrays;

public class ArrayStack<T> implements StackADT<T> {
    private final int DEFAULT_CAPACITY =100;

    private int top;
    private T[] stack;

    public ArrayStack()
    {
        top = 0;
        stack = (T[]) (new Object[DEFAULT_CAPACITY]);
    }

    /*使用默认容量创造一个空栈，参数initialCapacity表示的是指定容量*/
    public ArrayStack(int initialCapacity)
    {
        top = 0;
        stack = (T[])(new Object[initialCapacity]);
    }
    public void push(T element){
        if(size() == stack.length){
            expandCapacity();
        }
        stack[top] = element;
        top++;
    }
    private void expandCapacity()

    {
        stack = Arrays.copyOf(stack,stack.length * 2);
    }
    public T pop() throws EmptyCollectionException{
        if(isEmpty()) {
            throw new EmptyCollectionException("Stack");
        }
        top--;
        T result = stack[top];
        stack[top] = null;

        return result;
    }

    @Override
    public T peek() throws EmptyCollectionException
    {
      if(isEmpty()) {
          throw new EmptyCollectionException("Stack");
      }
      return stack[top-1];
    }
    @Override
    public boolean isEmpty()
    {
        // To be completed as a Programming Project
        if(size() == 0) {
            return true;
        } else {
            return false;
        }
    }
    @Override
    public int size()
    {
        // To be completed as a Programming Project
        return top;
    }
    @Override
    public String toString()
    {
        String line = "";
        // To be completed as a Programming Project
      for(int i = 0 ; i < top; i++)
      {
          line +=  stack[i]+"";
      }
      return line;
    }
}

